package com.ews.onlineexchange.dao;

import java.util.List;

import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

import com.ews.onlineexchange.model.Sector;

@Stateless
public class SectorDao {	
	
	@PersistenceContext
	private EntityManager entityManager;
	
	private static final String TREE_SQL = ""
			+ "	SELECT		sector.id, sector.sectorName, sector.parentSector_id "
			+ "	FROM		Sector sector"
			+ "	START WITH	sector.id = :rootId "
			+ "	CONNECT BY	sector.parentSector_id = PRIOR sector.id	";
	public List<Object[]> querySectorInTree(String rootId) {
		Query query = entityManager.createNativeQuery(TREE_SQL);
		query.setParameter("rootId", rootId);
		return query.getResultList();
	}
	
	private static final String JOIN_FETCH_SECTOR_EQL = ""
			+ "	SELECT			sector"
			+ "	FROM			Sector sector "
			+ "	LEFT JOIN FETCH	sector.childSectors child"
			+ "	WHERE			sector.id = :id	";	
	public Sector expandSector(Sector parent) {
		Query query = entityManager.createQuery(JOIN_FETCH_SECTOR_EQL);
		query.setParameter("id", parent.getId());
		return (Sector) query.getResultList().get(0);
	}
	
	
	/**
	 * 递归获取 rootSector
	 * @param sector
	 * @return
	 */
	public Sector getRootSector(Sector sector) {
		Sector parentSector = sector.getParentSector();
		if (null == parentSector) {
			return sector;
		} else {
			String parentSectorId = parentSector.getId();
			Sector parentSector_1 = entityManager.find(Sector.class, parentSectorId);
			return getRootSector(parentSector_1);
		}
	}


	public Sector find(String id) {
		return entityManager.find(Sector.class, id);		
	}
}
